package com.apping.module.edittext;

import java.lang.reflect.Field;

import com.apping.module.R;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class ImageEditTextAtv extends Activity implements OnClickListener {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.apping_image_edittext);
		initUI();
	}

	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("SplashScreen"); // 统计页面
		MobclickAgent.onResume(this); // 统计时长
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd("SplashScreen"); // 保证 onPageEnd 在onPause
													// 之前调用,因为 onPause 中会保存信息
		MobclickAgent.onPause(this);
	}

	public void initUI() {
		Button button1 = (Button) findViewById(R.id.image_for_button1);
		Button button2 = (Button) findViewById(R.id.image_for_button2);
		Button button3 = (Button) findViewById(R.id.image_for_button3);
		Button button4 = (Button) findViewById(R.id.image_for_button4);

		button1.setOnClickListener(this);
		button2.setOnClickListener(this);
		button3.setOnClickListener(this);
		button4.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		EditText editText = (EditText) findViewById(R.id.imageInputBox);
		Field field = null;
		if (v.getId() == R.id.image_for_button1) {
			try {
				field = R.drawable.class.getDeclaredField("img1");
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			}
		}

		if (v.getId() == R.id.image_for_button2) {
			try {
				field = R.drawable.class.getDeclaredField("img2");
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			}
		}

		if (v.getId() == R.id.image_for_button3) {
			try {
				field = R.drawable.class.getDeclaredField("img3");
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			}
		}
		if (v.getId() == R.id.image_for_button4) {
			try {
				field = R.drawable.class.getDeclaredField("img4");
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			}
		}
		try {
			int resourceId = Integer.parseInt(field.get(null).toString());
			Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
					resourceId);
			ImageSpan imageSpan = new ImageSpan(ImageEditTextAtv.this, bitmap);
			SpannableString spannableString = new SpannableString("i");
			spannableString.setSpan(imageSpan, 0, 1,
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

			editText.append(spannableString);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
